<template>
  <div class="todo-container">
    <div class="todo-wrap">
      <Header :addTodo="addTodo"/>
      <List :todos="todos" :deleteTodo="deleteTodo" :toggleTodo="toggleTodo"/>
      <Footer :todos="todos" :selectAll="selectAll" :clearCompletedTodos="clearCompletedTodos"/>

      <hr>
      <!-- <props-test name="tom" :myAge="-1"/> -->
    </div>
  </div>
</template>


<script>
  import Header from './components/Header.vue'
  import List from './components/List.vue'
  import Footer from './components/Footer.vue'
  import PropsTest from './test/PropsTest.vue'
  export default {
    name: 'App',

    data () {
      return {
        // 初始时就读取json数据并解析为js的数组, 如果没有指定为空数组
        todos: []
      }
    },

    mounted () {
      // 模拟异步加载得到todos数据
      setTimeout(() => {
        this.todos = JSON.parse(localStorage.getItem('todos_key')) || []
      }, 2000);
    },

    watch: {
      todos: {
        handler (value) {
          console.log('handler', value)
          // 将todos保存localStorage中 (必须保存json格式)
          localStorage.setItem('todos_key', JSON.stringify(value))
        },
        deep: true, // 深度监视 ==> 数组内部的对象内部数据变化都会触发
      }
    },

    // 数据在哪个组件, 更新数据的行为(函数)就定义在哪个组件
    methods: {
      // 添加todo
      addTodo (todo) {
        console.log('addTodo', todo)
        // 创建一个新的id, 并给todo
        todo.id = Date.now()
        // 添加到todos中
        this.todos.unshift(todo)
      },

      // 删除todo
      deleteTodo (index) {
        this.todos.splice(index, 1)
      },

      // 全选或全不选
      selectAll(isCheck) {
        this.todos.forEach(todo => todo.completed = isCheck)
      },

      // 消除已完成的
      clearCompletedTodos () {
        console.log('clearCompletedTodos()')
        this.todos = this.todos.filter(todo => !todo.completed)
      },
      // 将一个指定的todo切换勾选状态
      toggleTodo (todo) {
        todo.completed = !todo.completed
      }
    },

    components: {
      Header,
      List,
      Footer,
      PropsTest
    }
  }
</script>


<style scoped>
  .todo-container {
    width: 600px;
    margin: 0 auto;
  }
  .todo-container .todo-wrap {
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 5px;
  }
</style>